var tree_data;
var id_nodeid;
var nowSelected;

$('document').ready(
    function () {
        var data;
        //获取所有权限
        $.ajax({
            url: "/ajax/get_all_permission",
            success: function (result) {
                data = JSON.parse(result);
                //将数据转换到tree_data当中
                tree_data = build_tree(data);
                id_nodeid = {};
                makeMap(tree_data, -1, id_nodeid);
                initTree(tree_data);
            }
        });

    }
);

function makeMap(data, nowpath, id_nodeid) {
    if (data == null)
        return nowpath;
    var id = "";
    for (var i = 0; i < data.length; i++) {
        id = data[i]['id'];
        nowpath += 1;
        id_nodeid[id] = nowpath;
        nowpath = makeMap(data[i]['nodes'], nowpath, id_nodeid);
    }
    return nowpath;

}

function build_tree(data) {
    var res = [];
    for (var i = 0; i < data.length; i++) {
        var inf = data[i]['additionInf'].split(",");
        var son = build_tree(data[i]['sons']);
        if (son.length === 0)
            son = null;
        res.push({
            'text': inf[0],
            'id': inf[1],
            color: "#00CC00",
            backColor: "#FFFFFF",
            nodes: son
        })
    }
    return res;
}

function initTree(data) {
    $('#tree').treeview({
        data: data,         // 数据源
        showCheckbox: true,   //是否显示复选框
        highlightSelected: true,    //是否高亮选中
        //nodeIcon: 'glyphicon glyphicon-user',    //节点上的图标
        //nodeIcon: 'glyphicon glyphicon-globe',
        emptyIcon: '',    //没有子节点的节点图标
        multiSelect: false    //多选
    });
}

function freshTree(id) {
    $.ajax({
        url: "/ajax/get_role_permission?id=" + id,
        success: function (result) {
            //清除所有已点击的内容
            $('#tree').treeview('uncheckAll');
            //$('#tree').treeview('expandAll');
            result = JSON.parse(result);
            for (var i = 0; i < result.length; i++) {
                $('#tree').treeview('checkNode', id_nodeid[result[i]]);
            }
        }
    });
    nowSelected = id;
}

function save() {
    //$(this).attr("disabled","disabled");

    var checked = $('#tree').treeview("getChecked");
    var sendInf = [];
    for (var i = 0; i < checked.length; i++) {
        sendInf.push(checked[i]['id']);
    }
    $.ajax({
            url: "/API/set_role_permission?id=" + nowSelected,
            data: JSON.stringify(sendInf),
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            type: "POST",
            error: function () {
                location.reload(true);
            },
            success: function () {
                location.reload(true);
            }
        }
    );
}

